﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI;
using Windows.UI.ViewManagement;
using Windows8Accelerator.Core.Xaml;
using SimpleRssReader.DataSources;
using SimpleRssReader.Model;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml;
using Windows8Accelerator.Core.Xaml.ViewModels;
using Windows8Accelerator.Core.Xaml.Helpers;

namespace SimpleRssReader.ViewModel
{
    public class PostViewModel : ViewModelBase
    {
        public async Task LoadAsync(Post post)
        {
            Post = post;
            var cachedPost = await DataSource.CachedInstance.RetrieveFullPostAsync(post);
            Post = cachedPost.Object;

            if (cachedPost.CacheDate < DateTime.Now.AddHours(-1))
            {
                Post = await DataSource.Instance.RetrieveFullPostAsync(post);
            }

            if (!Blogs.Contains(post.Blog))
                Blogs.Add(post.Blog);
        }

        private Post _Post;
        public Post Post
        {
            get { return this._Post; }
            set { this.SetProperty(ref this._Post, value); }
        }

        private ObservableCollection<Blog> _Blogs = new ObservableCollection<Blog>();
        public ObservableCollection<Blog> Blogs
        {
            get { return this._Blogs; }
        }

        public static void GroupHeaderClick(object sender, Windows8Accelerator.Core.Xaml.Controls.SuperItemClickEventArgs e)
        {
            try
            {
                AppHelper.Frame.GoBack();
            }
            catch { }
            try
            {
                AppHelper.Frame.GoBack();
            }
            catch { }
            AppHelper.Frame.Navigate(typeof(BlogPage), e.Item);
        }

        public static void ItemClick(object sender, Windows8Accelerator.Core.Xaml.Controls.SuperItemClickEventArgs e)
        {
            try
            {
                AppHelper.Frame.GoBack();
            }
            catch { }
            AppHelper.Frame.Navigate(typeof(PostPage), e.Item);
        }
    }
}
